#! /usr/bin/env python3

import time
import traceback
import os

from selenium import webdriver
from selenium.webdriver.remote.webdriver import WebDriver
from selenium.webdriver.remote.webelement import WebElement
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait

from color_logging import Log


class KeyWords:
    def __init__(self):
        self.log = Log()

    @staticmethod
    def now() -> str:
        return time.strftime('%Y%m%d_%H%M%S', time.localtime(time.time()))
    
    @staticmethod
    def now_time() -> str:
        return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
        
    def open_page(self, url):
        """打开网页"""
        self.log.debug("实例化浏览器对象")
        self.driver = webdriver.Chrome()
        self.log.debug("设置隐匿等待10秒")
        self.driver.implicitly_wait(10)
        self.log.info("最大化浏览器窗口")
        self.driver.maximize_window()
        self.log.info(f"打开网页{url}")
        self.driver.get(url)
    
    def find_element(self, *args) -> WebElement or Exception:
        """定位元素"""
        return WebDriverWait(self.driver, 5, 0.5).until(
            lambda x: x.find_element(*args))
        
    def send_keys(self, *args):
        """输入内容"""
        self.log.info(f"通过{args[0]}定位元素{args[1]}，并输入内容 {args[2]}")
        ele = self.find_element(*args[:2])
        ele.clear()
        ele.send_keys(args[2])

    def click(self, *args):
        """点击元素"""
        self.log.info(f"通过{args[0]}方式定位元素{args[1]}后点击该元素")
        self.find_element(*args).click()

    def save_screenshot(self) -> str:
        """截图"""
        img_name = f"{self.now()}.png"
        img_dir = os.path.dirname(__file__)
        img_path = os.path.join(img_dir, 'image', img_name)
        self.driver.get_screenshot_as_file(img_path)
        self.log.info(f"屏幕截图已保存至 {img_path}")
        return img_path

    def quit(self):
        """退出网页"""
        self.log.info("关闭所有页面")
        self.driver.quit()
        
    def assert_msg(self, result):
        """通过页面的文本内容断言"""
        self.log.info(f"断言内容 {result} 是否在页面中")
        time.sleep(1)
        assert result in self.driver.page_source

    def assert_title(self, result):
        """通过页面的标题断言"""
        self.log.info(f"断言标题 {result} 是否与当前页面标题相同")
        assert result == self.driver.title

    def assert_url(self, result):
        """通过url断言"""
        self.log.info(f"断言网址 {result} 是否与当前页面网址相同")
        assert result == self.driver.current_url

    def assert_alert(self, result):
        """通过弹窗的文本内容断言"""
        # 强制等待，等待弹窗出现
        self.log.info(f"断言内容 {result} 是否在弹窗中")
        time.sleep(2)
        try:
            alert = self.driver.switch_to.alert
            assert result in alert.text
        except Exception as e:
            self.log.error(f"{type(e)} {str(e)}")
            assert result in str(e)

